<template>
  <div class="import-question-bank">
    <!-- 选项卡 -->
    <el-tabs v-model="activeTab" class="custom-tabs">
      <el-tab-pane label="选择题目" name="select">
        <!-- 筛选条件 -->
        <div class="filter-section">
          <div class="filter-controls">
            <div class="filter-item">
              <span class="label">课程：</span>
              <el-select
                v-model="selectedCourse"
                placeholder="请选择"
                style="width: 200px"
                @change="changeCourse"
              >
                <el-option
                  v-for="item in courseList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </div>
            <div class="filter-item">
              <span class="label">章节：</span>
              <el-select
                v-model="selectedChapter"
                placeholder="请选择"
                style="width: 200px"
                clearable
                :disabled="!selectedCourse"
                @change="chapterChange"
              >
                <el-option
                  v-for="item in chapterList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </div>
            <div class="filter-item">
              <span class="label">题目类型：</span>
              <el-select
                v-model="selectedType"
                placeholder="请选择"
                style="width: 200px"
                clearable
                :disabled="!selectedCourse"
                @change="questionTypeChange"
              >
                <el-option
                  v-for="item in questionTypeList"
                  :key="item.type"
                  :label="item.message"
                  :value="item.type"
                />
              </el-select>
            </div>
          </div>
          <div class="filter-actions">
            <el-button color="#457aff" type="primary" @click="saveQuestions"
              >保存</el-button
            >
          </div>
        </div>

        <!-- 题目表格 -->
        <div class="table-section">
          <el-table
            :data="questionsList"
            style="width: 100%"
            @selection-change="handleSelectionChange"
            ref="questionTable"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="title" label="试题题目" width="500">
              <template #default="{ row }">
                <span class="question-title">{{ row.content }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="questionTypeMessage"
              label="题目类型"
              width="120"
            />
            <el-table-column prop="courseName" label="课程" width="300" />
            <el-table-column prop="chapterName" label="章节" width="200" />
            <el-table-column label="操作" align="center" width="200">
              <template #default="{ row }">
                <el-button
                  style="color: #457aff"
                  text
                  type="primary"
                  @click="previewQuestion(row)"
                >
                  预览
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <el-tab-pane name="selected" v-if="false">
        <template #label>
          <span>已选择</span>
          <el-badge
            v-if="selectedQuestions.length > 0"
            :value="selectedQuestions.length"
            class="tab-badge"
          />
        </template>

        <!-- 操作按钮 -->
        <div class="selected-actions">
          <el-button
            type="danger"
            @click="deleteSelected"
            :disabled="toDeleteIds.length === 0"
          >
            删除
          </el-button>
          <el-button type="primary" color="#457aff" @click="saveQuestions"
            >保存</el-button
          >
        </div>

        <!-- 已选择题目表格 -->
        <div class="table-section">
          <el-table
            :data="selectedQuestions"
            style="width: 100%"
            @selection-change="handleDeleteSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="title" label="试题题目" width="500">
              <template #default="{ row }">
                <span class="question-title">{{ row.title }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="typeText" label="题目类型" width="120" />
            <el-table-column prop="course" label="课程" width="300" />
            <el-table-column prop="chapter" label="章节" width="200" />
            <el-table-column label="操作" align="center" width="200">
              <template #default="{ row }">
                <el-button
                  style="color: #457aff"
                  text
                  type="primary"
                  @click="previewQuestion(row)"
                >
                  预览
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 预览弹窗-->
    <el-dialog
      :close-on-click-modal="false"
      width="850"
      class="dialog-questions"
      v-model="dialogQuestion"
      center
    >
      <div class="dialog-content markdown-body">
        <div class="question-title" v-html="rowData.content"></div>
        <template v-if="rowData.questionType === 1">
          <div
            v-for="(item, index) in rowData.answer"
            :key="index"
            class="question-chose"
          >
            <span>{{ answerChose[index] }}：</span>
            <span class="question-flex" v-html="item.content"></span>
          </div>
        </template>
        <div class="question-answer">
          答案：
          <span
            v-if="rowData.questionType === 3"
            class="chose"
            style="font-family: '黑体'; font-size: 16px"
            v-html="answerTrue"
          ></span>
          <span v-else class="chose" v-html="answerTrue"></span>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            color="#155EEF"
            @click="dialogQuestion = false"
            >确 定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "make_importQuestionBank",
  data() {
    return {
      activeTab: "select",
      selectedCourse: "",
      selectedChapter: "",
      selectedType: "",
      selectedQuestions: [], // 已选择的题目
      toDeleteIds: [], // 待删除的题目
      courseList: [],
      chapterList: [],
      questionTypeList: [],
      questionsList: [],
      selectIds: [],
      questionNum: 0,
      dialogQuestion: false,
      rowData: {},
      answerChose: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"],
      answerTrue: "",
    };
  },
  created() {
    this.courseId = JSON.parse(localStorage.getItem("courseId"));
    this.getCourseList();
    this.getChapterList();
    this.getQuestionTypeList();
    this.getQuestionNum();
  },
  methods: {
    // 获取课程下拉数据
    getCourseList() {
      this.$axios.get("/tes/dropdown-list/course").then((res) => {
        this.courseList = res.data;
      });
    },
    changeCourse() {
      this.selectedChapter = "";
      this.selectedType = "";
      this.getQuestionList();
      this.getChapterList();
    },

    //获取课程下章节列表
    getChapterList() {
      this.$axios
        .get(`/tes/dropdown-list/course/${this.courseId}/chapter`)
        .then((res) => {
          this.chapterList = res.data;
        });
    },
    chapterChange() {
      this.getQuestionList();
    },

    //获取题目类型下拉
    getQuestionTypeList() {
      this.getQuestionNum();
      this.$axios
        .get(
          `/tes/course/${this.courseId}/businessType/1/question-repository/dropdown-list`
        )
        .then((res) => {
          this.questionTypeList = res.data.questionTypeList;
        });
    },
    questionTypeChange() {
      this.getQuestionList();
    },

    // 获取试题列表
    getQuestionList() {
      let params = new URLSearchParams();
      params.append("keyWord", "");
      params.append("courseId", this.selectedCourse);

      if (this.selectedChapter) {
        params.append("chapterId", this.selectedChapter);
      }

      if (this.selectedType) {
        params.append("questionType", this.selectedType);
      }

      this.$axios
        .get(
          `/tes/course/${
            this.courseId
          }/businessType/1/question-repository/preset?${params.toString()}`
        )
        .then((res) => {
          this.questionsList = res.data.map((item) => ({
            ...item,
            content: this.delHTMLLabel(item.content).replace(/\(\+\)/g, "（）"),
            chosen: false, // 确保初始状态为未选中
          }));
          // 同步表格选中状态
          this.$nextTick(() => {
            this.syncTableSelection();
          });
        });
    },

    // 删除html标签
    delHTMLLabel(str) {
      let reg = /<[^>]*>|<\/[^>]*>/gm;
      let result = str.replace(reg, "");
      return result;
    },

    //获取已选中题目数量
    getQuestionNum() {
      this.$axios
        .get(
          `/tes/course/${this.courseId}/businessType/1/question-repository/preset/chosen`
        )
        .then((res) => {
          this.questionNum = res.data.length;
        });
    },

    // 获取题目类型标签颜色
    getTypeTagType(type) {
      const typeMap = {
        choice: "primary",
        judge: "warning",
        fill: "success",
      };
      return typeMap[type] || "";
    },

    // 选择题目
    chooseQuestion() {
      this.$axios.post(
        `/tes/course/${this.courseId}/businessType/1/question-repository/preset/chosen`,
        {
          ids: this.selectIds,
        }
      );
    },

    // 处理题目选择变化
    handleSelectionChange(selection) {
      // 更新selectIds为选中的题目ID数组
      this.selectIds = selection.map((item) => item.id);

      // 同步更新questionsList中的chosen状态
      this.questionsList.forEach((item) => {
        item.chosen = selection.some((selected) => selected.id === item.id);
      });

      this.chooseQuestion();
    },

    // 处理删除选择变化
    handleDeleteSelectionChange(selection) {
      this.toDeleteIds = selection;
    },

    // 预览题目
    previewQuestion(row) {
      this.dialogQuestion = true;
      this.rowData = row;
      let answer = row.answer;
      this.answerTrue = "";
      //选择题
      if (row.questionType === 1) {
        //遍历找出正确答案选项
        answer.forEach((item, index) => {
          if (item.isCorrect) {
            this.answerTrue += this.answerChose[index];
          }
        });
      }
      //判断题
      if (row.questionType === 2) {
        if (answer[0].isCorrect) {
          this.answerTrue = "正确";
        } else {
          this.answerTrue = "错误";
        }
      }
      //填空题,简答，实验
      if (
        row.questionType === 3 ||
        row.questionType === 4 ||
        row.questionType === 9
      ) {
        this.answerTrue = answer[0].content;
      }
    },

    // 删除选中的题目
    deleteSelected() {
      if (this.toDeleteIds.length === 0) {
        this.$message.warning("请先选择要删除的题目");
        return;
      }

      const deleteIds = this.toDeleteIds.map((item) => item.id);
      this.selectedQuestions = this.selectedQuestions.filter(
        (q) => !deleteIds.includes(q.id)
      );
      this.toDeleteIds = [];
      this.$message.success("删除成功");
    },

    // 同步表格选中状态
    syncTableSelection() {
      if (this.$refs.questionTable) {
        // 清除所有选中状态
        this.$refs.questionTable.clearSelection();
        // 根据chosen状态重新选中
        this.questionsList.forEach((row) => {
          if (row.chosen) {
            this.$refs.questionTable.toggleRowSelection(row, true);
          }
        });
      }
    },

    // 保存题目
    saveQuestions() {
      if (this.selectIds.length === 0) {
        this.$message.warning("请先选择题目");
        return;
      }
      const loading = this.$loading({
        lock: true,
        text: "保存中...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.$axios
        .post(
          `/tes/course/${this.courseId}/businessType/1/question-repository/import-from-preset`,
          this.selectIds
        )
        .then((res) => {
          this.$message.success(`成功保存 ${this.selectIds.length} 道题目`);
          this.$router.push("/aiTeaching/courseBuild/makeQuestionBank");
        })
        .finally(() => {
          loading.close();
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.import-question-bank {
  padding: 40px 50px 40px 70px;
  background-color: #fff;
  box-sizing: border-box;

  .tab-badge {
    margin-left: 8px;
    :deep(.el-badge__content) {
      background-color: #ff4d4f;
      border: none;
    }
  }

  .filter-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 16px 0;

    .filter-controls {
      display: flex;
      align-items: center;
      gap: 24px;
    }

    .filter-item {
      display: flex;
      align-items: center;

      .label {
        font-size: 14px;
        color: #333;
        margin-right: 8px;
        white-space: nowrap;
      }
    }
  }

  .selected-actions {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 20px;
  }

  .table-section {
    .question-title {
      color: #333;
      line-height: 1.4;
    }

    :deep(.el-table) {
      font-size: 14px;
    }
  }

  .dialog-questions {
    .el-dialog__body {
      max-height: 500px;
      overflow: auto;
    }
    .dialog-content {
      padding: 20px 64px 0;
      .question-title {
        font-weight: bold;
        font-size: 16px;
        margin-bottom: 20px;
        p {
          line-height: 30px;
        }
      }
      .question-chose {
        font-size: 14px;
        line-height: 24px;
        padding: 6px 0;
        display: flex;
        align-items: center;
        .question-flex {
          flex: 1;
        }
        p {
          line-height: 24px;
        }
      }
      .question-answer {
        font-size: 16px;
        .chose {
          font-size: 18px;
          line-height: 30px;
          color: #385899;
          vertical-align: -2px;
          p {
            line-height: 30px;
          }
        }
        margin-top: 20px;
      }
    }
    .el-dialog__footer {
      text-align: center;
    }
  }
}
</style>
